package cn.com.dhc.danlu.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.jcodecraeer.xrecyclerview.ArrowRefreshHeader;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.lang.reflect.Field;

import cn.com.dhc.danlu.delegate.callback.IRefreshView;

/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-09-22
 * Time: 15:02
 * Description:  对XRecyclerView进行包装
 * user: do not setLoadingListener otherwise BaseListDataDelegate callback will not take effect
 */
public class DanluRecyclerView extends XRecyclerView implements XRecyclerView.LoadingListener {
    protected IRefreshView mRefreshView;
    private boolean mIsRefreshing;

    public DanluRecyclerView(Context context) {
        super(context);
        addDefaultRefreshListener();
    }

    public DanluRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        addDefaultRefreshListener();
    }

    public DanluRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        addDefaultRefreshListener();
    }

    private void addDefaultRefreshListener() {
        setLoadingListener(this);
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mIsRefreshing;
            }
        });
    }

    public void setRefreshView(IRefreshView mRefreshView) {
        this.mRefreshView = mRefreshView;
    }

    @Override
    public void onRefresh() {
        mIsRefreshing = true;
        if (null != mRefreshView) {
            mRefreshView.onRefresh(true);
        }
    }

    @Override
    public void onLoadMore() {
        mIsRefreshing = true;
        if (null != mRefreshView) {
            mRefreshView.onRefresh(false);
        }
    }

    @Override
    public void refreshComplete() {
        super.refreshComplete();
        mIsRefreshing = false;
    }

    @Override
    public void loadMoreComplete() {
        super.loadMoreComplete();
        mIsRefreshing = false;
    }

    public void setRefreshing() {
        try {
            Field refreshHeader = getClass().getSuperclass().getDeclaredField("mRefreshHeader");
            refreshHeader.setAccessible(true);
            ArrowRefreshHeader header = (ArrowRefreshHeader) refreshHeader.get(this);
            header.setState(ArrowRefreshHeader.STATE_REFRESHING);
            header.onMove(header.mMeasuredHeight);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
